/**
 * 资源树建造器
 * 参赞一个递归的树
 */
package cn.antia.cep.right;

import java.util.*;

import cn.antia.cep.common.*;
import cn.antia.cep.db.hibernate.bean.*;
import cn.antia.cep.db.hibernate.dao.*;

/**
 * @author sunkeei
 * 
 */
public class ResourceTreeBuilder extends TreeBuilder{
	private HibeGenericDAO hibeGenericDAO;
	public HibeGenericDAO getHibeGenericDAO() {
		return hibeGenericDAO;
	}
	public void setHibeGenericDAO(HibeGenericDAO resourceDAO) {
		this.hibeGenericDAO = resourceDAO;
	}
	

	/**
	 * 根据一个角色列表，返回一个资源树
	 *
     * @param roles 角色集合
     * @return RightTree
     * @throws cn.antia.cep.common.AntiaException a
     * @param resourceType resourceType*/
	public RightTree buildResourceTree(List roles)  throws AntiaException {
        if (roles == null || roles.size() < 1) {
            AntiaLog.warn("构建权限树时没有取到任何的角色。");
            return null;
        }
        List sysresources = hibeGenericDAO.find("from Resource where valid = 1");
        HashSet set = new HashSet();
        List allResource = new ArrayList();
        for (Iterator it = roles.iterator(); it.hasNext();) {
            Role o = (Role) it.next();
            set.addAll(queryResource(o,sysresources));
        }
        Object[] os = set.toArray();
        allResource = new ArrayList();
        for(int i = 0;i<os.length;i++){
        	allResource.add(os[i]);
        }
        return buildTree(allResource);
    }
	
	/**
	 * 根据一个角色，返回一个资源树
	 *
     * @param role 角色
     * @return 根据一个角色，返回一个资源树
     * @throws cn.antia.cep.common.AntiaException a
     * */
	public RightTree buildResourceTree(Role role) throws AntiaException {
		List sysresources = hibeGenericDAO.find("from Resource where valid = 1");
        HashSet set = queryResource(role,sysresources);
        Object[] os = set.toArray();
        List resources = new ArrayList();
        for(int i = 0;i<os.length;i++){
        	resources.add(os[i]);
        }
        return buildTree(resources);
    }

    //根据角色查询资源
    private HashSet queryResource(Role role,List sysresources) throws AntiaException {
    	HashSet ret = new HashSet();
    	if(role.getId().intValue() == DBFlag.ROLE_SUPER_MANAGER){
    		ret.addAll(sysresources);
    		return ret;
    	}
        RoleResource roleResource = new RoleResource();
		roleResource.setRoleId(role.getId());
		String hql;
		//if(resourceType == CommonConst.RESOURCE_ALL){
			hql = "select resourceId from RoleResource where roleId = " + role.getId();
			List urs = hibeGenericDAO.find(hql);
			
			Integer inttemp;
			Resource resource;
			for(int i = 0;i<urs.size();i++){
				inttemp = (Integer)urs.get(i);
				for(int j = 0;j<sysresources.size();j++){
					resource = (Resource)sysresources.get(j);
					if(inttemp.equals(resource.getId())){
						ret.add(resource);
						break;
					}
				}
			}
			return ret;
    }
}
